import {constantRouterMap} from "@/config/router.config";

const {isURL} = require("@/utils/validate");

const routers = {
    state: {
        routers: [],
    },
    mutations: {
        SET_ROUTERS: (state,routers) =>{
            state.routers = routers;
        },
    },
    actions: {
        generate: function ({commit}, permissions) {
            return new Promise(resolve => {
                let routers = generateRouters(permissions);
                constantRouterMap.concat(routers);
                commit('SET_ROUTERS',routers);
                resolve();
            });
        }
    }
}

function generateRouters(permissions) {
    return [
        {
            path: '/',
            name: 'index',
            component: resolve => require(['@comp/layout/Layout.vue'],resolve),
            meta: {title: '首页'},
            redirect: '/workplace',
            children: [
                ...generateChildRouters(permissions)
            ]
        },
        {
            "path": "*", "redirect": "/404", "hidden": true
        }
    ];

}

function generateChildRouters (permissions) {
    const routers = [];
    permissions.forEach(item => {
        let component;
        if(item.component.indexOf('layouts')>=0){
            component = resolve => require([`@comp/${item.component}.vue`],resolve);
        }else {
            component = resolve => require([`@views/${item.component}.vue`],resolve);
        }

        // URL支持{{ window.xxx }}占位符变量
        let URL = (item.url|| '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2))
        if (isURL(URL)) {
            item.url = URL;
        }

        let menu = {
            path: item.path,
            name: item.name,
            redirect: item.redirect,
            component: component,
            hidden: item.hidden,
            meta: {
                title: item.title,
                icon: item.icon,
                url: item.url,
                keepAlive:item.keepAlive,
                componentName: item.componentName
            }
        }

        if(item.alwaysShow){
            menu.alwaysShow = true;
            menu.redirect = menu.path;
        }

        if (item.children && item.children.length > 0) {
            menu.children = [...generateChildRouters( item.children)];
        }

        if(item.route && item.route === '0'){
            console.log(' 不生成路由 item.route：  '+item.route);
            console.log(' 不生成路由 item.path：  '+item.path);
        }else{
            routers.push(menu);
        }
    });
    return routers;
}

export default routers;
